<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="linux,">





  <link rel="alternate" href="/atom.xml" title="xingyys的个人站点" type="application/atom+xml">






<meta name="description" content="iscsi简单介绍iSCSI（Internet Small Computer System Interface，发音为/ˈаɪskʌzi/），Internet小型计算机系统接口，又称为IP-SAN，是一种基于因特网及SCSI-3协议下的存储技术，由IETF提出，并于2003年2月11日成为正式的标准。与传统的SCSI技术比较起来，iSCSI技术有以下三个革命性的变化：  把原来只用于本机的SCS">
<meta name="keywords" content="linux">
<meta property="og:type" content="article">
<meta property="og:title" content="iscsi共享磁盘服务">
<meta property="og:url" content="http://blog.xingyys.club/2019/01/26/iscsi共享磁盘服务/index.html">
<meta property="og:site_name" content="xingyys的个人站点">
<meta property="og:description" content="iscsi简单介绍iSCSI（Internet Small Computer System Interface，发音为/ˈаɪskʌzi/），Internet小型计算机系统接口，又称为IP-SAN，是一种基于因特网及SCSI-3协议下的存储技术，由IETF提出，并于2003年2月11日成为正式的标准。与传统的SCSI技术比较起来，iSCSI技术有以下三个革命性的变化：  把原来只用于本机的SCS">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://image.xingyys.club/blog/iscsi.jpg">
<meta property="og:updated_time" content="2019-02-14T04:57:00.461Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="iscsi共享磁盘服务">
<meta name="twitter:description" content="iscsi简单介绍iSCSI（Internet Small Computer System Interface，发音为/ˈаɪskʌzi/），Internet小型计算机系统接口，又称为IP-SAN，是一种基于因特网及SCSI-3协议下的存储技术，由IETF提出，并于2003年2月11日成为正式的标准。与传统的SCSI技术比较起来，iSCSI技术有以下三个革命性的变化：  把原来只用于本机的SCS">
<meta name="twitter:image" content="http://image.xingyys.club/blog/iscsi.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xingyys.club/2019/01/26/iscsi共享磁盘服务/">





  <title>iscsi共享磁盘服务 | xingyys的个人站点</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">xingyys的个人站点</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学习和分享</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-users"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xingyys.club/2019/01/26/iscsi共享磁盘服务/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="xingyys">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="xingyys的个人站点">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">iscsi共享磁盘服务</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-01-26T08:28:08+08:00">
                2019-01-26
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/运维/" itemprop="url" rel="index">
                    <span itemprop="name">运维</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="http://image.xingyys.club/blog/iscsi.jpg" alt=""></p>
<h1 id="iscsi简单介绍"><a href="#iscsi简单介绍" class="headerlink" title="iscsi简单介绍"></a>iscsi简单介绍</h1><p>iSCSI（Internet Small Computer System Interface，发音为/ˈаɪskʌzi/），Internet小型计算机系统接口，又称为IP-SAN，是一种基于因特网及SCSI-3协议下的存储技术，由IETF提出，并于2003年2月11日成为正式的标准。与传统的SCSI技术比较起来，iSCSI技术有以下三个革命性的变化：</p>
<ul>
<li>把原来只用于本机的SCSI协义透过TCP/IP网络发送，使连接距离可作无限的地域延伸；</li>
<li>连接的服务器数量无限（原来的SCSI-3的上限是15）；</li>
<li>由于是服务器架构，因此也可以实现在线扩容以至动态部署。</li>
</ul>
<p>简单的说就是tcp协议仿真scsi，将本地的磁盘通过网络共享给其他机器，提供数据的远程存储。</p>
<h1 id="iscsi基本概念"><a href="#iscsi基本概念" class="headerlink" title="iscsi基本概念"></a>iscsi基本概念</h1><p>iscsi中有一些常用的基本概念，了解这些能帮助我们认识iscsi服务的具体工作原理，下面就用一张图表来说明：</p>
<table>
<thead>
<tr>
<th>名词</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>ACL</td>
<td>访问权限控制列表，用来验证客户端启动器的访问，通常是客户端 iSCSI 启动器的 IQN 名称</td>
</tr>
<tr>
<td>IQN</td>
<td>用于标识单个 iSCSI 目标和启动器的唯一名称(全部小写)</td>
</tr>
<tr>
<td>WWN</td>
<td>用于标识单个光纤通道端口和节点的唯一编号</td>
</tr>
<tr>
<td>TARGET</td>
<td>iSCSI 服务器上的存储资源</td>
</tr>
<tr>
<td>LUN</td>
<td>iSCSI 服务器上的块设备</td>
</tr>
<tr>
<td>initiator(启动器)</td>
<td>以软件或硬件实施的 iSCSI 客户端</td>
</tr>
<tr>
<td>NODE</td>
<td>单个 iSCSI 启动器或者目标</td>
</tr>
<tr>
<td>TPG</td>
<td>启动器或者目标上的单个 IP 连接地址</td>
</tr>
<tr>
<td>Portal</td>
<td>网络接口及端口</td>
</tr>
</tbody>
</table>
<h1 id="iscsi-安装配置"><a href="#iscsi-安装配置" class="headerlink" title="iscsi 安装配置"></a>iscsi 安装配置</h1><p>iscsi  服务管理的软件有多个，这里就简单介绍两个，<code>targetcli</code>和<code>tgt</code>。</p>
<h2 id="使用targetcli管理配置iscsi"><a href="#使用targetcli管理配置iscsi" class="headerlink" title="使用targetcli管理配置iscsi"></a>使用targetcli管理配置iscsi</h2><p><strong>1.准备阶段</strong><br>有两台linux机器，分别作为服务端和客户端。实验环境最好在虚拟机上，方便修改的反复操作。同时在服务端上有一块磁盘作为iscsi共享磁盘。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">[root@localhost ~]<span class="comment"># lsblk </span></span><br><span class="line">NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT</span><br><span class="line">sda      8:0    0   40G  0 disk </span><br><span class="line">├─sda1   8:1    0  500M  0 part /boot</span><br><span class="line">├─sda2   8:2    0    4G  0 part [SWAP]</span><br><span class="line">└─sda3   8:3    0 35.5G  0 part /</span><br><span class="line">sdb      8:16   0   10G  0 disk </span><br><span class="line">└─sdb1   8:17   0   10G  0 part </span><br><span class="line">sdc      8:32   0   10G  0 disk </span><br><span class="line">sr0     11:0    1 1024M  0 rom</span><br></pre></td></tr></table></figure></p>
<p>这个选择<code>/dev/sdb1</code>,没有的同学可以使用<code>fdisk</code>命令自己分配一个。<br><strong>2.安装targetcli</strong><br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">yum install -y targetcli</span><br></pre></td></tr></table></figure></p>
<p>还需要启动targetcli服务<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">systemctl start target</span><br></pre></td></tr></table></figure></p>
<p><strong>3.配置targetcli</strong><br>配置targetcli有几个步骤，添加target，在target上添加lun，将target共享到指定网段。<br>先来创建一个块设备，使用命令为：<br><code>/backstores/block create westos:storage1 /dev/sdb1</code><br>进入targetcli操作：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">[root@localhost ~]<span class="comment"># targetcli</span></span><br><span class="line">Warning: Could not load preferences file /root/.targetcli/prefs.bin.</span><br><span class="line">targetcli shell version 2.1.fb46</span><br><span class="line">Copyright 2011-2013 by Datera, Inc and others.</span><br><span class="line">For <span class="built_in">help</span> on commands, <span class="built_in">type</span> <span class="string">'help'</span>.</span><br><span class="line"></span><br><span class="line">/&gt; /backstores/block create westos:storage1 /dev/sdb1</span><br><span class="line">Created block storage object westos:storage1 using /dev/sdb1. <span class="comment"># 注意这里就成功创建一个快设备</span></span><br><span class="line">/&gt; ls</span><br><span class="line">o- / ......................................................................................................................... [...]</span><br><span class="line">  o- backstores .............................................................................................................. [...]</span><br><span class="line">  | o- block .................................................................................................. [Storage Objects: 1]</span><br><span class="line">  | | o- westos:storage1 .............................................................. [/dev/sdb1 (0 bytes) write-thru deactivated]</span><br><span class="line">  | |   o- alua ................................................................................................... [ALUA Groups: 1]</span><br><span class="line">  | |     o- default_tg_pt_gp ....................................................................... [ALUA state: Active/optimized]</span><br><span class="line">  | o- fileio ................................................................................................. [Storage Objects: 0]</span><br><span class="line">  | o- pscsi .................................................................................................. [Storage Objects: 0]</span><br><span class="line">  | o- ramdisk ................................................................................................ [Storage Objects: 0]</span><br><span class="line">  o- iscsi ............................................................................................................ [Targets: 0]</span><br><span class="line">  o- loopback ......................................................................................................... [Targets: 0]</span><br><span class="line">/&gt;</span><br></pre></td></tr></table></figure></p>
<p>接着创建一个iscsi共享的target，使用命令为：<br><code>/iscsi create iqn.2018-10.com.westos:storage1</code><br>这里的target名称其实可以随意，但一般格式为<code>iqn.year.month.com.domain.xxx</code>,<br>执行的结果如下：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">/&gt; /iscsi create iqn.2018-10.com.westos:storage1</span><br><span class="line">Created target iqn.2018-10.com.westos:storage1.</span><br><span class="line">Created TPG 1.</span><br><span class="line">Global pref auto_add_default_portal=<span class="literal">true</span></span><br><span class="line">Created default portal listening on all IPs (0.0.0.0), port 3260.</span><br><span class="line">/&gt; ls</span><br><span class="line">o- / ......................................................................................................................... [...]</span><br><span class="line">  o- backstores .............................................................................................................. [...]</span><br><span class="line">  | o- block .................................................................................................. [Storage Objects: 1]</span><br><span class="line">  | | o- westos:storage1 .............................................................. [/dev/sdb1 (0 bytes) write-thru deactivated]</span><br><span class="line">  | |   o- alua ................................................................................................... [ALUA Groups: 1]</span><br><span class="line">  | |     o- default_tg_pt_gp ....................................................................... [ALUA state: Active/optimized]</span><br><span class="line">  | o- fileio ................................................................................................. [Storage Objects: 0]</span><br><span class="line">  | o- pscsi .................................................................................................. [Storage Objects: 0]</span><br><span class="line">  | o- ramdisk ................................................................................................ [Storage Objects: 0]</span><br><span class="line">  o- iscsi ............................................................................................................ [Targets: 1]</span><br><span class="line">  | o- iqn.2018-10.com.westos:storage1 ................................................................................... [TPGs: 1]</span><br><span class="line">  |   o- tpg1 ............................................................................................... [no-gen-acls, no-auth]</span><br><span class="line">  |     o- acls .......................................................................................................... [ACLs: 0]</span><br><span class="line">  |     o- luns .......................................................................................................... [LUNs: 0]</span><br><span class="line">  |     o- portals .................................................................................................... [Portals: 1]</span><br><span class="line">  |       o- 0.0.0.0:3260 ..................................................................................................... [OK]</span><br><span class="line">  o- loopback ......................................................................................................... [Targets: 0]</span><br><span class="line">/&gt;</span><br></pre></td></tr></table></figure></p>
<p>之后还需要将target共享出去：<br><code>/iscsi/iqn.2018-06.com.westos:storage1/tpg1/acls create iqn.2018-06.com.example:westoskey</code> #cal配置<br><code>/iscsi/iqn.2018-06.com.westos:storage1/tpg1/luns create /backstores/block/westos:storage1</code> #luns配置<br><code>/iscsi/iqn.2018-06.com.westos:storage1/tpg1/portals/ create 172.25.254.101</code> #portals配置<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">/&gt; /iscsi/iqn.2018-10.com.westos:storage1/tpg1/acls create iqn.2018-10.com.example:westoskey</span><br><span class="line">Created Node ACL <span class="keyword">for</span> iqn.2018-10.com.example:westoskey</span><br><span class="line">/&gt; /iscsi/iqn.2018-10.com.westos:storage1/tpg1/luns create /backstores/block/westos:storage1</span><br><span class="line">Created LUN 0.</span><br><span class="line">Created LUN 0-&gt;0 mapping <span class="keyword">in</span> node ACL iqn.2018-10.com.example:westoskey</span><br><span class="line">/&gt; /iscsi/iqn.2018-10.com.westos:storage1/tpg1/portals/ create 192.168.3.150</span><br><span class="line">Using default IP port 3260</span><br><span class="line">Could not create NetworkPortal <span class="keyword">in</span> configFS</span><br><span class="line">/&gt; ls</span><br><span class="line">o- / ............................................................................................................. [...]</span><br><span class="line">  o- backstores .................................................................................................. [...]</span><br><span class="line">  | o- block ...................................................................................... [Storage Objects: 1]</span><br><span class="line">  | | o- westos:storage1 .................................................... [/dev/sdb1 (0 bytes) write-thru activated]</span><br><span class="line">  | |   o- alua ....................................................................................... [ALUA Groups: 1]</span><br><span class="line">  | |     o- default_tg_pt_gp ........................................................... [ALUA state: Active/optimized]</span><br><span class="line">  | o- fileio ..................................................................................... [Storage Objects: 0]</span><br><span class="line">  | o- pscsi ...................................................................................... [Storage Objects: 0]</span><br><span class="line">  | o- ramdisk .................................................................................... [Storage Objects: 0]</span><br><span class="line">  o- iscsi ................................................................................................ [Targets: 1]</span><br><span class="line">  | o- iqn.2018-10.com.westos:storage1 ....................................................................... [TPGs: 1]</span><br><span class="line">  |   o- tpg1 ................................................................................... [no-gen-acls, no-auth]</span><br><span class="line">  |     o- acls .............................................................................................. [ACLs: 1]</span><br><span class="line">  |     | o- iqn.2018-10.com.example:westoskey ........................................................ [Mapped LUNs: 1]</span><br><span class="line">  |     |   o- mapped_lun0 ........................................................... [lun0 block/westos:storage1 (rw)]</span><br><span class="line">  |     o- luns .............................................................................................. [LUNs: 1]</span><br><span class="line">  |     | o- lun0 ............................................... [block/westos:storage1 (/dev/sdb1) (default_tg_pt_gp)]</span><br><span class="line">  |     o- portals ........................................................................................ [Portals: 1]</span><br><span class="line">  |       o- 0.0.0.0:3260 ......................................................................................... [OK]</span><br><span class="line">  o- loopback ............................................................................................. [Targets: 0]</span><br><span class="line">/&gt;</span><br></pre></td></tr></table></figure></p>
<p>有一个报错信息：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Could not create NetworkPortal in configFS</span><br></pre></td></tr></table></figure></p>
<p>原因是再/iscsi/portals/下已经存在IP地址。可以直接跳过，获取删除，重新创建。<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">/&gt; /iscsi/iqn.2018-10.com.westos:storage1/tpg1/portals/ delete 0.0.0.0 3260</span><br><span class="line">Deleted network portal 0.0.0.0:3260</span><br><span class="line">/&gt; /iscsi/iqn.2018-10.com.westos:storage1/tpg1/portals/ create 192.168.3.150</span><br><span class="line">Using default IP port 3260</span><br><span class="line">Created network portal 192.168.3.150:3260.</span><br><span class="line">/&gt; ls</span><br><span class="line">o- / ............................................................................................................. [...]</span><br><span class="line">  o- backstores .................................................................................................. [...]</span><br><span class="line">  | o- block ...................................................................................... [Storage Objects: 1]</span><br><span class="line">  | | o- westos:storage1 .................................................... [/dev/sdb1 (0 bytes) write-thru activated]</span><br><span class="line">  | |   o- alua ....................................................................................... [ALUA Groups: 1]</span><br><span class="line">  | |     o- default_tg_pt_gp ........................................................... [ALUA state: Active/optimized]</span><br><span class="line">  | o- fileio ..................................................................................... [Storage Objects: 0]</span><br><span class="line">  | o- pscsi ...................................................................................... [Storage Objects: 0]</span><br><span class="line">  | o- ramdisk .................................................................................... [Storage Objects: 0]</span><br><span class="line">  o- iscsi ................................................................................................ [Targets: 1]</span><br><span class="line">  | o- iqn.2018-10.com.westos:storage1 ....................................................................... [TPGs: 1]</span><br><span class="line">  |   o- tpg1 ................................................................................... [no-gen-acls, no-auth]</span><br><span class="line">  |     o- acls .............................................................................................. [ACLs: 1]</span><br><span class="line">  |     | o- iqn.2018-10.com.example:westoskey ........................................................ [Mapped LUNs: 1]</span><br><span class="line">  |     |   o- mapped_lun0 ........................................................... [lun0 block/westos:storage1 (rw)]</span><br><span class="line">  |     o- luns .............................................................................................. [LUNs: 1]</span><br><span class="line">  |     | o- lun0 ............................................... [block/westos:storage1 (/dev/sdb1) (default_tg_pt_gp)]</span><br><span class="line">  |     o- portals ........................................................................................ [Portals: 1]</span><br><span class="line">  |       o- 192.168.3.150:3260 ................................................................................... [OK]</span><br><span class="line">  o- loopback ............................................................................................. [Targets: 0]</span><br><span class="line">/&gt;</span><br><span class="line">/&gt; <span class="built_in">exit</span></span><br><span class="line">Global pref auto_save_on_exit=<span class="literal">true</span></span><br><span class="line">Last 10 configs saved <span class="keyword">in</span> /etc/target/backup/.</span><br><span class="line">Configuration saved to /etc/target/saveconfig.json</span><br></pre></td></tr></table></figure></p>
<p>退出之后配置结果持久化到<code>/etc/target/saveconfig.json</code>。</p>
<h2 id="使用tgt配置iscsi"><a href="#使用tgt配置iscsi" class="headerlink" title="使用tgt配置iscsi"></a>使用tgt配置iscsi</h2><p>再来介绍另外一种软件，就是tgt。<br><strong>1.安装</strong><br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">yum install -y epel-release</span><br><span class="line">yum install -y scsi-target-utils</span><br></pre></td></tr></table></figure></p>
<p>启动服务<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">systemctl start tgtd</span><br></pre></td></tr></table></figure></p>
<p><strong>2.配置tgt</strong><br>配置tgt使用的命令是<code>tgtadm</code>，有以下常用选项：</p>
<ul>
<li>–lld <driver> –mode target –op new –tid <id> –targetname <name> # 新建target</name></id></driver></li>
<li>–lld <driver> –mode target –op delete [–force] –tid <id>  # 删除target</id></driver></li>
<li>–lld <driver> –mode target –op show # 查看所有的target</driver></li>
<li>–lld <driver> –mode target –op show –tid <id> # 查看指定id的target</id></driver></li>
<li>–lld <driver> –mode target –op update –tid <id> –name <param> –value <value> # 更新target</value></id></driver></li>
<li>–lld <driver> –mode target –op bind –tid <id> –initiator-address <address> # target共享到指定网段</address></id></driver></li>
<li>–lld <driver> –mode target –op bind –tid <id> –initiator-name <name> # target共享到指定的客户端名称</name></id></driver></li>
<li>–lld <driver> –mode target –op unbind –tid <id> –initiator-address <address> # 解绑</address></id></driver></li>
<li>–lld <driver> –mode target –op unbind –tid <id> –initiator-name <name></name></id></driver></li>
<li>–lld <driver> –mode logicalunit –op new –tid <id> –lun <lun><br>–backing-store <path> –bstype <type> –bsopts <bs options=""> –bsoflags <options> # 创建lun</options></bs></type></path></lun></id></driver></li>
<li>–lld <driver> –mode logicalunit –op delete –tid <id> –lun <lun> # 删除lun</lun></id></driver></li>
<li>–lld <driver> –mode account –op new –user <name> –password <pass> # 添加认证</pass></name></driver></li>
<li>–lld <driver> –mode account –op delete –user <name> # 删除认证</name></driver></li>
<li>–lld <driver> –mode account –op bind –tid <id> –user <name> [–outgoing] # 绑定认证 </name></id></driver></li>
<li>–lld <driver> –mode account –op unbind –tid <id> –user <name> [–outgoing] # 解绑认证</name></id></driver></li>
</ul>
<p>添加target<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">[root@localhost ~]<span class="comment"># tgtadm --lld iscsi --mode target --op new --tid 1 --targetname iqn-2019-11.com.iscsi.test</span></span><br><span class="line">[root@localhost ~]<span class="comment"># tgtadm --lld iscsi --mode target --op show</span></span><br><span class="line">Target 1: iqn-2019-11.com.iscsi.test</span><br><span class="line">    System information:</span><br><span class="line">        Driver: iscsi</span><br><span class="line">        State: ready</span><br><span class="line">    I_T nexus information:</span><br><span class="line">    LUN information:</span><br><span class="line">        LUN: 0</span><br><span class="line">            Type: controller</span><br><span class="line">            SCSI ID: IET     00010000</span><br><span class="line">            SCSI SN: beaf10</span><br><span class="line">            Size: 0 MB, Block size: 1</span><br><span class="line">            Online: Yes</span><br><span class="line">            Removable media: No</span><br><span class="line">            Prevent removal: No</span><br><span class="line">            Readonly: No</span><br><span class="line">            SWP: No</span><br><span class="line">            Thin-provisioning: No</span><br><span class="line">            Backing store <span class="built_in">type</span>: null</span><br><span class="line">            Backing store path: None</span><br><span class="line">            Backing store flags: </span><br><span class="line">    Account information:</span><br><span class="line">    ACL information:</span><br></pre></td></tr></table></figure></p>
<p>添加lun<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">[root@localhost ~]<span class="comment"># tgtadm --lld iscsi --mode logicalunit --op new --tid 1 --lun 22 -b /dev/sdb</span></span><br><span class="line">[root@localhost ~]<span class="comment"># tgtadm --lld iscsi --mode target --op show</span></span><br><span class="line">Target 1: iqn-2019-11.com.iscsi.test</span><br><span class="line">    System information:</span><br><span class="line">        Driver: iscsi</span><br><span class="line">        State: ready</span><br><span class="line">    I_T nexus information:</span><br><span class="line">    LUN information:</span><br><span class="line">        LUN: 0</span><br><span class="line">            Type: controller</span><br><span class="line">            SCSI ID: IET     00010000</span><br><span class="line">            SCSI SN: beaf10</span><br><span class="line">            Size: 0 MB, Block size: 1</span><br><span class="line">            Online: Yes</span><br><span class="line">            Removable media: No</span><br><span class="line">            Prevent removal: No</span><br><span class="line">            Readonly: No</span><br><span class="line">            SWP: No</span><br><span class="line">            Thin-provisioning: No</span><br><span class="line">            Backing store <span class="built_in">type</span>: null</span><br><span class="line">            Backing store path: None</span><br><span class="line">            Backing store flags: </span><br><span class="line">        LUN: 22</span><br><span class="line">            Type: disk</span><br><span class="line">            SCSI ID: IET     00010016</span><br><span class="line">            SCSI SN: beaf122</span><br><span class="line">            Size: 10737 MB, Block size: 512</span><br><span class="line">            Online: Yes</span><br><span class="line">            Removable media: No</span><br><span class="line">            Prevent removal: No</span><br><span class="line">            Readonly: No</span><br><span class="line">            SWP: No</span><br><span class="line">            Thin-provisioning: No</span><br><span class="line">            Backing store <span class="built_in">type</span>: rdwr</span><br><span class="line">            Backing store path: /dev/sdb</span><br><span class="line">            Backing store flags: </span><br><span class="line">    Account information:</span><br><span class="line">    ACL information:</span><br></pre></td></tr></table></figure></p>
<p>注：这里有一个小提示，每个lun中的<code>SCSI ID</code>项是在客户端中的唯一标识，它的值是根据<code>target id</code>和<code>lun id</code>计算得到的，即：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SCSI ID = Target ID转16进制(前四位) + Lun ID转16进制(后四位)</span><br></pre></td></tr></table></figure></p>
<p>所以lun 22的<code>SCSI ID</code>为<code>00010016</code><br>共享到客户端：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[root@localhost ~]<span class="comment"># tgtadm --lld iscsi --mode target --op bind --tid 1 --initiator-address 192.168.3.131</span></span><br></pre></td></tr></table></figure></p>
<h2 id="客户端连接"><a href="#客户端连接" class="headerlink" title="客户端连接"></a>客户端连接</h2><p><strong>1.安装客户端</strong><br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">yum install -y epel-release</span><br><span class="line">yum install -y iscsi-initiator-utils</span><br></pre></td></tr></table></figure></p>
<p>客户端命令：</p>
<ul>
<li>iscsiadm -m session # 查看所有会话</li>
<li>iscsiadm -m discovery -t st -p 192.168.3.150 #查看共享target</li>
<li>iscsiadm -m node -T iqn.2018-10.com.westos:storage1 -p 192.168.3.150 -l #登陆连接</li>
<li>iscsiadm -m node -T iqn.2018-10.com.westos:storage1 -u #退出登陆</li>
<li>iscsiadm -m node -T iqn.2018-10.com.westos:storage1 -o delete #删除登陆数据</li>
</ul>
<p><strong>2.发现设备</strong><br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[root@localhost ~]<span class="comment"># iscsiadm -m discovery -t st -p 192.168.3.150</span></span><br><span class="line">192.168.3.150:3260,1 iqn.2018-10.com.westos:storage1</span><br></pre></td></tr></table></figure></p>
<p>登录<br>注：请关闭防火墙和selinux<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">[root@localhost mnt]<span class="comment"># iscsiadm -m node -T iqn.2018-10.com.westos:storage1 -p 192.168.3.150 -l</span></span><br><span class="line">Logging <span class="keyword">in</span> to [iface: default, target: iqn.2018-10.com.westos:storage1, portal: 192.168.3.150,3260] (multiple)</span><br><span class="line">Login to [iface: default, target: iqn.2018-10.com.westos:storage1, portal: 192.168.3.150,3260] successful.</span><br><span class="line">[root@localhost ~]<span class="comment"># lsblk </span></span><br><span class="line">NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT</span><br><span class="line">fd0      2:0    1    4K  0 disk </span><br><span class="line">sda      8:0    0   40G  0 disk </span><br><span class="line">├─sda1   8:1    0  500M  0 part /boot</span><br><span class="line">├─sda2   8:2    0    8G  0 part [SWAP]</span><br><span class="line">└─sda3   8:3    0 31.5G  0 part /</span><br><span class="line">sdb      8:16   0    2G  0 disk </span><br><span class="line">└─sdb1   8:17   0    2G  0 part </span><br><span class="line">sr0     11:0    1 1024M  0 rom</span><br></pre></td></tr></table></figure></p>
<p>同时在<code>/dev/disk/by-id</code>下生成块设备。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="xingyys 微信支付">
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/linux/" rel="tag"># linux</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/01/24/数据结构和算法的基本定义/" rel="next" title="数据结构和算法的基本定义">
                <i class="fa fa-chevron-left"></i> 数据结构和算法的基本定义
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/01/26/linux上使用udev创建裸设备/" rel="prev" title="linux上使用udev创建裸设备">
                linux上使用udev创建裸设备 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MjIyNC8xODc3MQ=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpeg" alt="xingyys">
            
              <p class="site-author-name" itemprop="name">xingyys</p>
              <p class="site-description motion-element" itemprop="description">你的话是我脚前的灯，是我路上的光。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/xingyys" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#iscsi简单介绍"><span class="nav-number">1.</span> <span class="nav-text">iscsi简单介绍</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#iscsi基本概念"><span class="nav-number">2.</span> <span class="nav-text">iscsi基本概念</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#iscsi-安装配置"><span class="nav-number">3.</span> <span class="nav-text">iscsi 安装配置</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#使用targetcli管理配置iscsi"><span class="nav-number">3.1.</span> <span class="nav-text">使用targetcli管理配置iscsi</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用tgt配置iscsi"><span class="nav-number">3.2.</span> <span class="nav-text">使用tgt配置iscsi</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#客户端连接"><span class="nav-number">3.3.</span> <span class="nav-text">客户端连接</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-snowflake-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xingyys</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
